﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form name="myForm">

        <div id="richedit" style=" height:200px; width : 90%  ; border :1px solid black " contenteditable="true"></div>
        <div id="menu" onclick="try {  myExecCommand(event) } catch (e) { alert(e.message)}">
            <input type="button" value="加粗选中文本" id="Bold" />
            <input type="button" value="转化为斜体" id="Italic" />
            <input type="button" value="字体变红" id="Red" />
            <input type="button" value="测试富文本选区" id="testGetSelection" />
        </div>
        <div>
            <input type="submit" value="提交" />
        </div>
    </form>
    <script type="text/javascript">

        var richEdit = (function () {
            return {
                selectedBold: function () {
                    document.execCommand("bold", false, null);
                },
                selectedItalic: function () {
                    document.execCommand("italic", false, null);
                },
                selectedRed: function () {
                    document.execCommand("forecolor", false, "red");
                },
                testGetSelection: function () {
                    var selection = document.getSelection();
                    var firstNode = selection.anchorNode;
                    var lastNode = selection.focusNode;
                }
            }
        })(); 

        //execCommand是javascript中的关键字， 不能用来定义函数
        function myExecCommand(event) {
            switch (event.target.id) {
                case "Bold": richEdit.selectedBold(); break;
                case "Italic": richEdit.selectedItalic(); break;
                case "Red": richEdit.selectedRed(); break;
                case "testGetSelection": richEdit.testGetSelection(); break;
            }
        }

        window.onload = function () {
            var myDiv = document.getElementById("richedit").innerHTML = "<p>123</p><p>456</p><p>789</p>";

            //表单提交前获得富文本编辑器中的内容
            document.forms["myForm"].addEventListener("submit", function (event) {
                var richEditHtml = document.getElementById("richedit").innerHTML;
                alert(richEditHtml);
                event.preventDefault();
            }, false);

        }
    </script>
</body>
</html>
